import React from 'react';
import {connect} from 'dva/index';
import {Button, Checkbox, Col, DatePicker, Form, Input, Popconfirm, Radio, Row, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RevenueDetail from '../../components/finance/revenueDetail';
import RightBox from '../../components/common/rightBox';
import {download} from '../../utils/commons';

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
const statusArr = ['删除', '草稿', '已提交'];
const FormItem = Form.Item;
const R = require("ramda");

const revenue = Form.create()(class Revenue extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({ type: 'revenue/getListForPage', payload: { ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE) } });
    }

    handleOpen = (id, disabled, status, approval) => {
        this.props.dispatch({
            type: 'revenue/getRevenueById',
            payload: { id }
        })
        if (status === '2') {
            //查询已锁定的费用
            this.props.dispatch({
                type: 'revenue/getListByBevenueId',
                payload: {
                    revenueId: id,
                    ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE)
                }
            });
        }
        if (approval) {
            //查询本次审核的费用
            this.props.dispatch({
                type: 'revenue/getListByBevenueId',
                payload: {
                    revenueId: id,
                    status: '2',
                    approval,
                    ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE)
                }
            });
        }
        this.props.dispatch({ type: 'history/queryRevenue', payload: {} }); //客户来账收账信息下拉
        // 第二个参数claim : true 代表认领动作打开窗口
        this.revenueDetail.handleOpen(disabled, false, approval);
    }

    handleSearch = (flag) => {
        let values = this.props.form.getFieldsValue();
        let newPage = R.pick(['page', 'size'], this.props.revenue.page);
        values.never = values.condition && values.condition.includes("never");
        values.balance = values.condition && values.condition.includes("balance");
        values.done = values.condition && values.condition.includes("done");
        values.approval = values.condition && values.condition.includes("approval");
        values.condition = undefined;
        values.receiveBegin = values.receiveDate ? values.receiveDate[0].format(Constants.DATEFORMAT) : undefined;
        values.receiveEnd = values.receiveDate ? values.receiveDate[1].format(Constants.DATEFORMAT) : undefined;
        values.receiveDate = undefined;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'revenue/getListForPage',
            payload: {
                ...values,
                ...newPage
            }
        });
    };

    handleDelete = id => {
        this.props.dispatch({
            type: 'revenue/deleteRevenueById',
            payload: {
                id,
                onSuccess: this.handleSearch
            }
        })
    }

    handleExport = (revenueId) => {
        let url = apiPath.mc + "/api/revenue/generate";
        download(url, {revenueId});
    }

    columns = [
        { title: '流水号', dataIndex: 'seqNo', key: 'seqNo' },
        { title: '凭证编号', dataIndex: 'selfNo', key: 'selfNo' },
        { title: '付款人名称', dataIndex: 'name', key: 'name' },
        { title: '来账账号', dataIndex: 'account', key: 'account' },
        { title: '来账银行', dataIndex: 'bank', key: 'bank' },
        { title: '币种', dataIndex: 'currency', key: 'currency' },
        { title: '来账金额', dataIndex: 'amount', key: 'amount' },
        { title: '余额', dataIndex: 'balance', key: 'balance' },
        { title: '来账日期', dataIndex: 'receiveDate', key: 'receiveDate' },
        { title: '状态', key: 'status', render: (text, record, index) => { return <span>{statusArr[record.status]}</span> } },
        {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                let deleteLink = <Popconfirm placement="leftTop" onConfirm={this.handleDelete.bind(this, record.id)} okText="是" cancelText="否" title={'是否确认删除'}>
                    <a href="#">删除</a>
                </Popconfirm>
                deleteLink = <RightBox resource={RightConstants.FINANCE.FINANCE_REVENUE_DELETE} split={true}>{deleteLink}</RightBox>

                let editLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, false, record.status, false)}>编辑</a>
                editLink = <RightBox resource={RightConstants.FINANCE.FINANCE_REVENUE_EDIT} split={true}>{editLink}</RightBox>

                let approvalLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, record.status, true)}>审核</a>
                approvalLink = <RightBox resource={RightConstants.FINANCE.FINANCE_REVENUE_APPROVAL} split={true}>{approvalLink}</RightBox>

                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, record.status, false)}>查看</a>

                let gennerate = <RightBox resource={RightConstants.FINANCE.FINANCE_REVENUE_EXPORT} split={true}><a href="#" onClick={this.handleExport.bind(this, record.id)}>导出</a></RightBox>

                editLink = record.status === '1' ? editLink : null;
                deleteLink = record.status === '1' || record.amount === record.balance ? deleteLink : null;
                approvalLink = record.approval > 0 ? approvalLink : null;
                gennerate = record.status === '2' ? gennerate : null;
                return <span>{approvalLink}{editLink}{deleteLink}{gennerate}{viewLink}</span>;
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        let formItemLayout2 = { labelCol: { span: 5 }, wrapperCol: { span: 19 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        values.never = values.condition && values.condition.includes("never");
        values.balance = values.condition && values.condition.includes("balance");
        values.done = values.condition && values.condition.includes("done");
        values.approval = values.condition && values.condition.includes("approval");
        values.condition = undefined;
        values.receiveBegin = values.receiveDate ? values.receiveDate[0].format(Constants.DATEFORMAT) : undefined;
        values.receiveEnd = values.receiveDate ? values.receiveDate[1].format(Constants.DATEFORMAT) : undefined;
        values.receiveDate = undefined;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.revenue.page.size,
            current: this.props.revenue.page.page,
            total: this.props.revenue.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = R.pick(['page', 'size'], this.props.revenue.page);
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'revenue/getListForPage',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = R.pick(['page', 'size'], this.props.revenue.page);
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'revenue/getListForPage',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            }
        }

        return (
            <div>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('name')(<Input />)}</FormItem></Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'来账日期'}>
                            {getFieldDecorator('receiveDate')(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>

                </Row>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'凭证编号'}>{getFieldDecorator('selfNo')(<Input />)}</FormItem></Col>
                    <Col span={11} style={{ marginLeft: 12 }}>
                        <FormItem {...formItemLayout2} label={'余额情况'} >
                            {getFieldDecorator('condition')
                                (<CheckboxGroup style={{ width: '100%' }}>
                                    <Checkbox value="never">从未认领</Checkbox>
                                    <Checkbox value="balance">可认领</Checkbox>
                                    <Checkbox value="done">认领完毕</Checkbox>
                                    <Checkbox value="approval">需审核</Checkbox>
                                </CheckboxGroup>)}
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('status', {
                                initialValue: ""
                            })(
                                <RadioGroup style={{ width: "100%" }} >
                                    <Radio value="">全部</Radio>
                                    <Radio value="1">{statusArr[1]}</Radio>
                                    <Radio value="2">{statusArr[2]}</Radio>
                                </RadioGroup>
                                )}
                        </FormItem>
                    </Col>
                    <Col span={8} style={{ float: 'left', marginLeft: 115 }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }}
                            onClick={this.handleSearch.bind(this, true)}>查询</Button>
                        <RightBox resource={RightConstants.FINANCE.FINANCE_REVENUE_ADD}>
                            <Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleOpen.bind(this, null, false)} size={'default'}>新增来账</Button></RightBox>
                    </Col>
                </Row>
                <Table loading={this.props.loading} rowKey='id' dataSource={this.props.revenue.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />
                <RevenueDetail wrappedComponentRef={(inst) => this.revenueDetail = inst} refreshList={this.handleSearch} />
            </div>
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.revenue, revenue: state.revenue
    };
}

export default connect(mapStateToProps)(revenue);
